package com.future.controller;

import com.future.exception.CodeException;
import com.future.pojo.Judge;
import com.future.pojo.Musiclist;
import com.future.pojo.Users;
import com.future.service.MusicService;
import com.future.service.UserService;
import com.future.tool.MailTool;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private MusicService musicService;

    //创建Judge实体类
    Judge judge = new Judge();

    //验证码
    @RequestMapping("/getCode")
    @ResponseBody
    @ApiOperation("验证码接口")
    public boolean getCode(String email , HttpServletRequest request,HttpSession session){
        //随机生成一个验证码
        String str="0123456789";
        String code =new String();
        for(int i=0;i<4;i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            code += ch;
        }
        Integer codes = Integer.parseInt(code);
        session.setAttribute("code",code);
        Date date = new Date();
        long time = date.getTime();
        session.setAttribute("time1",time);
        new Thread(
                () -> MailTool.send(email,codes)
        ).start();
        return true;
    }


    @ApiOperation("注册接口")
    @ResponseBody
    @GetMapping("/register")
    public Judge register(String userHao, String userPwd, String userEmail, String code,
                          HttpServletRequest request,HttpSession session) throws CodeException {
        String codeId = (String) request.getSession().getAttribute("code");
        int numss = userService.checkEmail(userEmail);
        if(numss == 1){
            Judge judge = new Judge();
            judge.setStatusCode(-3);
            judge.setInfo("该邮箱已被注册！");
            return judge;
        }else {
            int nums = userService.checkUserHao(userHao, "普通用户");
            if (nums != 1) {
                Date date = new Date();
                long time = date.getTime();
                long time1 = (long) session.getAttribute("time1");
                //设置验证码有效时间为3分钟
                if ((time - time1) / 1000 > 300) {
                    codeId = null;
                    session.removeAttribute("code");
                }
                if (code.equals(codeId)) {
                    //默认用户名为future
                    String userName = "future";
                    int num = userService.addUser(userName, userHao, userPwd, userEmail);
                    Judge judge = new Judge();
                    judge.setStatusCode(0);
                    judge.setInfo("注册成功！");
                    Users user = userService.checkHao(userHao);
                    int id = user.getUserId();
                    Musiclist musiclist = new Musiclist();
                    musiclist.setUserId(id);
                    int s = musicService.addloveMusiclist(musiclist);
                    musicService.addDownMusiclist(musiclist);
                    return judge;
                } else {
                    throw new CodeException("验证码错误！");
                }
            } else {
                judge.setStatusCode(-2);
                judge.setInfo("该账号已被注册！");
                return judge;
            }
        }
    }

    @ApiOperation("绑定账号")
    @RequestMapping("/bindCount")
    @ResponseBody
    public Judge bindCount(String userHao,HttpSession session){
        Users user = userService.userHaoEnroll(userHao);
        if(user!=null){
            String id = (String)session.getAttribute("Id");
            int num = userService.bindCount(userHao,id);
            if(num==1){
                judge.setInfo("绑定成功");
                return judge;
            }else {
                judge.setInfo("绑定失败");
                return judge;
            }
        }else{
            judge.setInfo("账号不存在");
            return judge;
        }
    }

    @ApiOperation("登录接口")
    @RequestMapping("/login")
    @ResponseBody
    public Judge userLogin(String userHao, String password,HttpSession session)  {
        String userPwd;
        String userLv;
        //登陆方式，邮箱登录和账号登录
        if(userHao.contains("@")){
            Users user = userService.userEmailEnrrol(userHao);
            if(user!=null){
                userPwd = user.getUserPwd();
                userLv = user.getUserLv();
                if (userPwd.equals(password)) {
                    if (userLv.equals("普通用户") || userLv.equals("歌手") || userLv.equals("会员")) {
                        judge.setStatusCode(1);
                        judge.setInfo("/future/");
                        session.setAttribute("USer",user);
                        return judge;
                    }else{
                        judge.setStatusCode(0);
                        judge.setInfo("/future/admin/queryAllUsers");
                        session.setAttribute("admin",user);
                        return judge;
                    }
                } else {
                    //密码错误
                    judge.setStatusCode(-1);
                    return judge;
                }
            }else{
                judge.setStatusCode(-1);
                return judge;
            }

        }else{
            //账号登录
            Users user = userService.userHaoEnroll(userHao);
            if(user != null) {
                userPwd = user.getUserPwd();
                userLv = user.getUserLv();
                //根据用户不同等级跳转到不同页面
                if (userPwd.equals(password)) {
                    if (userLv.equals("普通用户") || userLv.equals("歌手") || userLv.equals("会员")) {
                        judge.setStatusCode(1);
                        judge.setInfo("/future/");
                        session.setAttribute("User", user);
                    } else {
                        judge.setStatusCode(0);
                        judge.setInfo("/future/admin/queryAllUsers");
                        session.setAttribute("admin", user);
                    }
                } else {
                    //密码错误
                    judge.setStatusCode(-1);
                }
            }else{
                judge.setStatusCode(-1);
            }
            return judge;
        }
    }

    @ApiOperation("修改密码,填写账号")
    @PostMapping("/lost-Hao")
    @ResponseBody
    public Judge userHao(String userHao,HttpSession session){
        Judge judge = new Judge();
        //检查账号是否存在
        Users user = userService.checkHao(userHao);
        if(user==null){
            judge.setStatusCode(-1);
            judge.setInfo("账号不存在");
        }else{
            String userEmail = user.getUserEmail();
            session.setAttribute("userEmail",userEmail);
            session.setAttribute("changeHao",userHao);
            judge.setStatusCode(1);
            judge.setInfo("");
        }
        return judge;
    }

    @ApiOperation("修改密码,获取验证码")
    @PostMapping("/lost-code")
    @ResponseBody
    public Judge lostPassword(String code,HttpServletRequest request,HttpSession session){
        //得到邮箱发送的验证码
        String codeId = (String) request.getSession().getAttribute("code");
        Date date = new Date();
        long time = date.getTime();
        long time1 = (long) session.getAttribute("time1");
        //设置验证码有效时间为3分钟
        if((time - time1)/1000 > 300){
            codeId = null;
            session.removeAttribute("code");
        }
        //比较验证码
        if (code.equals(codeId)){
            judge.setStatusCode(0);
            judge.setInfo("验证成功！");
        }else{
            judge.setStatusCode(-1);
            judge.setInfo("验证码错误！");
        }
        return judge;

    }


    @ApiOperation("修改密码")
    @PostMapping("/checkPwd")
    @ResponseBody
    public Judge checkPwd(String pwdone,String pwdtwo,HttpSession session){
        Judge judge = new Judge();
        if (pwdone.equals(pwdtwo)){
            int num = userService.changePwd((String)session.getAttribute("changeHao"),pwdone);
            if(num==1){
                judge.setStatusCode(1);
                judge.setInfo("修改成功！");
            }else{
                judge.setStatusCode(0);
                judge.setInfo("修改失败，请重试！");
            }
        }else{
            judge.setStatusCode(-1);
            judge.setInfo("两次密码输入不同，请重新检查！");
        }
        return judge;
    }


    @ApiOperation(value = "用户更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true),
            @ApiImplicitParam(name = "userBirth", value = "用户生日", required = true),
            @ApiImplicitParam(name = "userName", value = "用户名字", required = true),
            @ApiImplicitParam(name = "userEmail", value = "用户邮箱", required = true),
            @ApiImplicitParam(name = "userGen", value = "用户性别", required = true)
    })
    @GetMapping("/updateuserUser")
    @ResponseBody
    public Judge updateuserUser(int userId, String userName, String userEmail, String userBirth,char userGen,HttpSession session) {
        int result = userService.updateuserUser(userId, userName, userEmail,userBirth, userGen);
        Judge judge = new Judge();
        if (result > 0) {
            if(session.getAttribute("User")!=null){
                Users USER = (Users)session.getAttribute("User");
                Users user = userService.userHaoEnroll(USER.getUserHao());
                session.removeAttribute("User");
                session.setAttribute("User",user);
            }else if(session.getAttribute("USer")!=null){
                Users USER = (Users)session.getAttribute("USer");
                Users user = userService.userEmailEnrrol(USER.getUserEmail());
                session.removeAttribute("USer");
                session.setAttribute("USer",user);
            }else{
                Users USER = (Users)session.getAttribute("user");
                Users user = userService.giteeLogin(USER.getId());
                session.removeAttribute("user");
                session.setAttribute("user",user);
            }
            judge.setInfo("修改成功！");
            judge.setStatusCode(1);
        } else {
            judge.setInfo("修改失败！");
            judge.setStatusCode(0);
        }
        return judge;
    }


    @ApiOperation(value = "注销账号")
    @PostMapping("/deleteMe")
    @ResponseBody
    public Judge deleteMe(String password, int userId, Model model) {
        String Pwd = userService.queryMyPwd(userId);
        if (password.equals(Pwd)) {
            int result = userService.deleteMe(userId);
            if (result > 0) {
                judge.setInfo("注销成功！");
                judge.setStatusCode(1);
            } else {
                judge.setInfo("注销失败！");
                judge.setStatusCode(0);
            }
        } else {
            judge.setInfo("密码验证失败！");
            judge.setStatusCode(0);
        }
        return judge;
    }

    @ApiOperation(value = "申请成为歌手")
    @PostMapping("/changeSinger")
    @ResponseBody
    public Judge changeSinger(int userId, Model model) {
        int result = userService.changeSinger(userId);
        if (result > 0) {
            judge.setInfo("申请成功！请等待管理员处理！");
            judge.setStatusCode(1);
        } else {
            judge.setInfo("申请失败！");
            judge.setStatusCode(0);
        }
        return judge;
    }





}
